<template>
	<view>
		<view v-if='contents && contents.length > 0'>
			<view v-for='item in contents' style='padding:10px;'>
				<view @click='toUrl(`/pages/content/index?id=${item.id}`)'>
					<img :src='item.cover' style='width:100%' />
					<view class='title'>{{item.title}}</view>
				</view>
			</view>
			<u-loadmore :status="status" />
		</view>
		<view v-else style='margin-top:30vh'>
			<u-empty
			        mode="list"
			>
			</u-empty>
		</view>
	</view>
</template>
 
<script>
	export default {
		data() {
			return {
				contents: [],
				page: 1,
				limit: 10,
				categoryId: 0,
				status: 'loadmore'
			}
		},
		onReachBottom() {
			if(this.status == 'loadmore'){
				this.page++
				this.getContentes()
			}
		},
		onLoad(options) {
			if(typeof(options.id) !== 'undefined'){
				this.categoryId = options.id
				let token = uni.getStorageSync('api_token')
				this.request.get(`api/categories`,{
					'@filter': `entity.getId() == ${options.id}`
				}).then((res) => {
					console.log('ccc',res.data)
					uni.setNavigationBarTitle({
						title: res.data[0].name
					})
				})
				if(token == ''){
					this.wxLogin()
				}else{
					this.getContents()
				}
			}else{
				uni.showModal({
					title: '',
					content: '参数错误',
					showCancel: false,
					success: () => {
						uni.switchTab({
							url: '/pages/index/index'
						})
					}
				})
			}
		},
		methods: {
			getContents(){
				this.request.get(`api/contents`,{
					'@filter': `entity.getCategory().getId() == ${this.categoryId}`,
					limit: this.limit,
					page: this.page,
					'@order': `entity.createdTime|DESC`
				}).then((res) => {
					console.log(res.data)
					if(res.data && res.data.length < this.limit){
						this.status = 'nomore'
					}
					for(let i of res.data){
						this.contents.push(i)
					}
				})
			},
			toUrl(page){
				uni.redirectTo({
					url: page
				})
			},
			wxLogin(){
				let _this = this
				uni.login({
					provider: "weixin",
					success: function(res) {
						let data = {
							code: res.code
						}
						_this.request.get("wechat/mini/login", data).then((res) => {
							if (res.data.token) {
								uni.setStorageSync('api_token', res.data.token);
								_this.getContents()
							}
						})
					},
				});
			},
		}
	}
</script>

<style>
	title{
		color: #909399;
		padding: 10px;
	}
</style>